"""
@author: Sergiy Tsymbalyuk
"""

import logging
from datetime import datetime
from markdown import markdown

from pylons import tmpl_context as c, url, request
from pylons.i18n import lazy_ugettext as _
from pylons.controllers.util import redirect

from repoze.what.plugins.pylonshq import ActionProtector
from repoze.what.predicates import in_group

from chowa.lib.base import BaseController, Session, render
from chowa.lib.site.navigation import Tab
from chowa.lib.site.forms import TabularFieldSet
from chowa.model.site import Page

log = logging.getLogger(__name__)

class PagesController(BaseController):
    def view(self, id):
        c.page = Session.query(Page).filter_by(name=id).one()
        c.content = markdown(c.page.content) if c.page.content else ''
        fs = TabularFieldSet(c.page)
        fs.configure(include=[fs.title, fs.content.textarea(size=(25, 10))])
        c.form = fs.render()
        c.is_admin = in_group('administrators').is_met(request.environ)
        return render('/site/page.html')
    
    @ActionProtector(in_group('administrators'))
    def save(self, id):
        if request.method == 'POST':
            page = Session.query(Page).filter_by(name=id).one()
            fs = TabularFieldSet(page, data=request.POST)
            fs.configure(include=[fs.title, fs.content])
            fs.model.modified = datetime.now()
            fs.sync()
            Session.commit()
        return redirect(url.current(action='view'))
    